package main

import (
	"database/sql"
	_ "github.com/go-sql-driver/mysql"
	"reflect"
)

var database *sql.DB

// InitDb 初始化数据库
func InitDb(username string, password string, ip string, dbname string) {
	db, err := sql.Open("mysql", username+":"+password+"@tcp("+ip+")/"+dbname)
	if err != nil {
		panic(err)
	}
	err = db.Ping()
	if err != nil {
		panic(err)
	}
	database = db
}

// CloseDb 关闭数据库连接
func CloseDb() {
	err := database.Close()
	if err != nil {
		panic(err)
	}
}

// Query 使用反射将数据库查询结果赋值到结构体字段
func Query(des interface{}, sql string, param ...any) {
	rows, err := database.Query(sql, param...)
	if err != nil {
		panic(err)
	}
	defer rows.Close()
	//从数据库查出来的字段名数组
	columns, _ := rows.Columns()
	values := make([]interface{}, len(columns))
	for i, v := range columns {
		var v2 = []rune(v)
		//首字母转大写
		v2[0] -= 'a' - 'A'
		values[i] = reflect.ValueOf(des).Elem().FieldByName(string(v2)).Addr().Interface()
	}
	for rows.Next() {
		err = rows.Scan(values...)
		if err != nil {
			panic(err)
		}
	}
}

// Exec 执行sql但不返回行数据
func Exec(sql string, param ...any) sql.Result {
	result, err := database.Exec(sql, param...)
	if err != nil {
		panic(err)
	}
	return result
}
